import Axios from 'axios'
import { Loading, Message } from 'element-ui'
import {merge} from 'lodash'
function plugin (Vue) {
  if (plugin.installed) {
    return
  }
  Axios.defaults.withCredentials = true
  Axios.defaults.headers.post['Content-Type'] = 'application/json'
  let loading = null
  // 请求拦截
  let service = process.env.BASE_API
  Axios.interceptors.request.use(config => {
    config.url = service + config.url
    // token exists mean that you have logged in
    if (config.data && config.data.api_login) {
      let _data = {}
      _data = merge(_data, config.data)
      _data = `${JSON.stringify(_data)}`
      config.data = _data
    } else {
      let token = Vue.localStorage.get(Vue.const.COOKIE.KEY_TOKEN)
      if (token) {
        config.headers.token = token
        let _data = {}
        _data = merge(_data, config.data)
        _data = `${JSON.stringify(_data)}`
        config.data = _data
      } else {
        // Message.warning('请重新登录！')
        // Store.dispatch('LOGOUT') // 暂时注释掉 此处调用logout接口
        // setTimeout(() => {
        //   location.href = '/#/login'
        // }, 1000)
      }
    }
    if (config.loading !== false) {
      loading = Loading.service({
        background: 'rgba(0, 0, 0, 0.1)'
      })
    }
    return config
  }, err => {
    return Promise.reject(err)
  })
  // 请求结束
  Axios.interceptors.response.use(response => {
    if (!response.data.success) {
      if (response.data.errorCode === 1001) {
        // 容错处理
      }
      if (response.data.errcode === 50014) {
        Vue.localStorage.remove(Vue.const.SAVEWEBINFO)
        Message.error({
          title: '操作提示',
          message: response.data.msg
        })
        setTimeout(() => {
          location.href = '/#/login'
        }, 1000)
      }
    }
    if (response.config.loading !== false) {
      loading.close()
    }
    return response.data
  }, error => {
    console.log('error: ', error)
    loading && loading.close()
    Message.error({
      title: '操作提示',
      message: '网络异常, 请刷新重试'
    })
    return Promise.reject(error)
  })

  Vue.req = (() => {
    return Axios
  }).call(this)

  Object.defineProperties(Vue.prototype, {
    $http: {
      get () {
        return Axios
      }
    }
  })
}

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(plugin)
}

export default plugin
